package me.fanwu.services.alipay.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayOpenAuthTokenAppQueryRequest;
import com.alipay.api.request.AlipayOpenAuthTokenAppRequest;
import com.alipay.api.response.AlipayOpenAuthTokenAppQueryResponse;
import com.alipay.api.response.AlipayOpenAuthTokenAppResponse;
import com.google.common.collect.ImmutableMap;
import me.fanwu.services.alipay.AuthService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/*
 * Wupher 编写于 2016/11/2.
 */
@Service
@SuppressWarnings("unused")
class AuthServiceImpl implements AuthService {
    private static final Logger log =  LoggerFactory.getLogger(AuthServiceImpl.class);

    private AlipayClient alipayClient;

    @Autowired
    public AuthServiceImpl(AlipayClient alipayClient) {
        this.alipayClient = alipayClient;
    }

    @Override
    public String retrieveAuthToken(String authCode) throws AlipayApiException {
        AlipayOpenAuthTokenAppRequest request = new AlipayOpenAuthTokenAppRequest();
        Map<String, String> reqMap = ImmutableMap.of("grant_type", "authorization_code", "code", authCode);
        String reqJson = JSON.toJSONString(reqMap);

        log.info("req: " + reqJson);
        request.setBizContent(reqJson);
        AlipayOpenAuthTokenAppResponse response = alipayClient.execute(request);
        if (response.isSuccess()){
            return response.getAppAuthToken();
        }
        return null;
    }

    @Override
    public String getAuthTokenInfo(String authToken) throws AlipayApiException {
        AlipayOpenAuthTokenAppQueryRequest request = new AlipayOpenAuthTokenAppQueryRequest();
        Map<String, String > req = ImmutableMap.of("app_auth_token", authToken);
        String reqJson = JSON.toJSONString(req);
        request.setBizContent(reqJson);
        AlipayOpenAuthTokenAppQueryResponse response = alipayClient.execute(request);

        return response.getBody();
    }
}
